from django import forms
from django.utils.translation import gettext_lazy as _
from accounts.models import User
from .models import Project, ProjectMember, ProjectTag, Webhook, Announcement

class ProjectForm(forms.ModelForm):
    """项目表单"""
    class Meta:
        model = Project
        fields = ('name', 'description')
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入项目名称')}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'placeholder': _('请输入项目描述'), 'rows': 4}),
        }
        labels = {
            'name': _('项目名称'),
            'description': _('项目描述'),
        }

class ProjectMemberForm(forms.ModelForm):
    """项目成员表单"""
    # 使用用户名搜索用户
    user = forms.ModelChoiceField(
        queryset=User.objects.all(),
        label=_('用户'),
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    class Meta:
        model = ProjectMember
        fields = ('user', 'role')
        widgets = {
            'role': forms.Select(attrs={'class': 'form-control'}),
        }
        labels = {
            'role': _('角色'),
        }

class ProjectTagForm(forms.ModelForm):
    """项目标签表单"""
    # 提供一些预设颜色选项
    COLOR_CHOICES = (
        ('#1677ff', _('蓝色')),
        ('#52c41a', _('绿色')),
        ('#faad14', _('橙色')),
        ('#f5222d', _('红色')),
        ('#722ed1', _('紫色')),
        ('#13c2c2', _('青色')),
        ('#fa8c16', _('琥珀色')),
        ('#f759ab', _('粉色')),
        ('#597ef7', _('靛蓝色')),
        ('#fadb14', _('黄色')),
    )
    
    color = forms.ChoiceField(
        choices=COLOR_CHOICES,
        label=_('标签颜色'),
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    class Meta:
        model = ProjectTag
        fields = ('name', 'color')
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入标签名称')}),
        }
        labels = {
            'name': _('标签名称'),
        }


class WebhookForm(forms.ModelForm):
    """Webhook表单"""
    # 使用多选框选择事件类型
    events = forms.MultipleChoiceField(
        choices=Webhook.EVENT_CHOICES,
        label=_('触发事件'),
        widget=forms.CheckboxSelectMultiple,
        help_text=_('选择哪些事件会触发Webhook通知')
    )
    
    class Meta:
        model = Webhook
        fields = ('name', 'url', 'channel', 'secret', 'events', 'is_active')
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control', 
                'placeholder': _('请输入Webhook名称')
            }),
            'url': forms.URLInput(attrs={
                'class': 'form-control', 
                'placeholder': _('请输入接收Webhook通知的URL地址')
            }),
            'channel': forms.Select(attrs={
                'class': 'form-control',
            }),
            'secret': forms.TextInput(attrs={
                'class': 'form-control', 
                'placeholder': _('用于验证Webhook请求的签名密钥，留空则不进行签名验证')
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
            })
        }
        labels = {
            'name': _('Webhook名称'),
            'url': _('Webhook URL'),
            'channel': _('渠道'),
            'secret': _('签名密钥'),
            'events': _('触发事件'),
            'is_active': _('是否激活'),
        }
        help_texts = {
            'channel': _('选择Webhook通知的渠道'),
            'secret': _('用于验证Webhook请求的签名密钥，留空则不进行签名验证'),
            'is_active': _('设置为关闭则不会发送任何Webhook通知'),
        }
    
    def __init__(self, *args, **kwargs):
        """初始化表单，设置events字段的初始值和自动生成URL"""
        # 获取project参数，用于在保存时设置关联的项目
        self.project = kwargs.pop('project', None)
        super().__init__(*args, **kwargs)
        
        # 记录是否是新建模式
        self.is_new = not (self.instance and self.instance.pk)
        
        # 如果是编辑模式，设置events字段的初始值
        if not self.is_new:
            self.fields['events'].initial = self.instance.events
        # 如果是新建模式，自动生成URL地址并设置默认事件为报警信息
        else:
            self.fields['events'].initial = ['alarm']  # 默认选择报警信息
            # 简化的逻辑：只要是新建模式且有project参数，就自动生成URL
            if self.project:
                # 自动生成URL
                self.initial['url'] = self._generate_webhook_url()
                # 添加一个提示，说明可以修改这个URL
                self.fields['url'].help_text = _('系统已自动生成建议的URL格式，您可以根据需要修改它')
                # 添加一个自定义属性，用于在模板中添加刷新按钮
                self.fields['url'].widget.attrs['data-generate-url'] = 'true'
    
    def _generate_webhook_url(self):
        """生成一个唯一的Webhook URL示例"""
        import uuid
        from django.conf import settings
        # 生成基于项目名称和UUID的唯一标识符
        project_slug = self.project.name.lower().replace(' ', '-')[:20]
        # 生成一个完整的UUID作为示例（实际保存时会使用Webhook对象的真实ID）
        webhook_id = str(uuid.uuid4())
        
        # 使用项目设置中的实际域名，而不是示例域名
        base_url = settings.SITE_DOMAIN
        # 生成与项目URL配置匹配的Webhook接收地址格式 - 确保末尾有斜杠
        return f"{base_url}/webhooks/{project_slug}/{webhook_id}/receive/"
    
    def save(self, commit=True):
        """保存Webhook实例，设置关联的项目"""
        instance = super().save(commit=False)
        
        # 设置关联的项目
        if self.project:
            instance.project = self.project
        
        # 将events字段的值从列表转换为JSON格式
        instance.events = self.cleaned_data['events']
        
        if commit:
            instance.save()
            # 保存后，如果是新创建的Webhook，使用真实的Webhook ID更新URL
            if self.is_new:
                from django.conf import settings
                project_slug = self.project.name.lower().replace(' ', '-')[:20]
                base_url = settings.SITE_DOMAIN
                # 使用真实的Webhook ID生成正确的URL - 确保末尾有斜杠
                instance.url = f"{base_url}/webhooks/{project_slug}/{instance.id}/receive/"
                instance.save()
        
        return instance


class AnnouncementForm(forms.ModelForm):
    """公告表单"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 配置标签字段
        self.fields['tags'].queryset = ProjectTag.objects.all()
        self.fields['tags'].widget = forms.CheckboxSelectMultiple()
        self.fields['tags'].required = False
        self.fields['tags'].help_text = _('选择要发布公告的目标项目标签，不选择则为全局公告')
        
    class Meta:
        model = Announcement
        fields = ['title', 'content', 'tags', 'is_active']
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('请输入公告标题')
            }),
            'content': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 5,
                'placeholder': _('请输入公告内容')
            }),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
        labels = {
            'title': _('公告标题'),
            'content': _('公告内容'),
            'tags': _('目标标签'),
            'is_active': _('是否激活'),
        }
        help_texts = {
            'tags': _('选择要发送公告的项目标签，留空则发送给所有项目'),
            'is_active': _('设置为关闭则不会发送给新项目'),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 获取所有项目标签
        self.fields['tags'].queryset = ProjectTag.objects.all()
        self.fields['tags'].required = False